#include "firstwindow.h"
#include "ui_firstwindow.h"

#include <QApplication>
#include <QWidget>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QDebug>
#include <QCompleter>
#include <QListView>
#include <QMap>
#include <QListWidgetItem>
#include <mainwindow.h>
#include <QSizePolicy>
#include <QScrollArea>
#include <user.h>
#include "main.h"



firstwindow::firstwindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::firstwindow)
{
    ui->setupUi(this);
    //message的布局
    message_playout = new QVBoxLayout();
    //最先放入，会在所有信息的最下方
    QLabel* end = new QLabel;
    end->setText("——以上是所有可展示的最新消息——");
    message_playout->addWidget(end);

    //那边布局莫名其妙不起作用，重新弄一个
    QVBoxLayout *all_layout = new QVBoxLayout(this);
    all_layout->setContentsMargins(0, 0, 0, 0);
    all_layout->setSpacing(0);
    all_layout->addWidget(ui->head);
    all_layout->addWidget(ui->search);
    all_layout->addWidget(ui->caidan);
    all_layout->addWidget(ui->mainwindow);

    all_layout->setStretchFactor(ui->head, 3);
    all_layout->setStretchFactor(ui->search, 1);
    all_layout->setStretchFactor(ui->caidan, 1);
    all_layout->setStretchFactor(ui->mainwindow, 17);
    this->setLayout(all_layout);

    //修改标题栏，为了方便测试生成一个本人用户,合并时传入即可
    this->setWindowTitle("IM_software");
    this->setWindowIcon(QIcon(":/new/prefix1/images/icons_head.png"));
    user* user1 = new user(use_uid,use_name,use_ip,"学生",QPixmap(":/new/prefix1/images/123.jpg"));
    me = user1;

    show_me();//展示个人信息


    //确保数据库更新完毕，（不过auto模式的槽链接一般情况下不会换线程（我认为
    while(!load_friend_over){
        QThread::sleep(100);
    }
    m_socket = new SerSocket();
    connect(this,&firstwindow::heart_jump,m_socket,&SerSocket::Jump);
    connect(m_socket,&SerSocket::ServerSendUnreadMsg,this,&firstwindow::getUpdateMessage);
    connect(m_socket,&SerSocket::ServerSendUpdateList,this,&firstwindow::getUpdateUserlist);
    connect(m_socket,&SerSocket::ServerSendUnreadFile,this,&firstwindow::getUpdateFileLists);

    QVector<Friend> f_list = db.GetAllFriends();
    for(auto f:f_list){
        //        user_list.push_back(user(QString::number(f.id),f.name,f.ip,f.job));
        user* newUser = new user(QString::number(f.id),f.name,f.ip,f.job);
        userMap.insert(QString::number(f.id), newUser);
    }

    QVector<Group> g_list = db.GetAllGroups();
    for(auto g:g_list){
        //        user_list.push_back(user(QString::number(f.id),f.name,f.ip,f.job));
        group* newGroup = new group(use_uid,QString::number(g.id),g.name,g.memberlist,QPixmap(""),"0",g.category);
        groupMap.insert(QString::number(g.id), newGroup);
    }

    //根据传入列表产生页面内容
    //    page_message = new QWidget();
    //    page_friends = new QWidget();
    //    page_groups = new QWidget();
    //    page_search = new QWidget();

    show_message();
    show_friends();//相当于调用初始化
    show_groups();
    show_search();

    //    messagewindow * page_message = new messagewindow(this);
    //    friendwindow * page_firends = new friendwindow(this);
    //    mainwindow * page_message = new mainwindow;
    //    mainwindow * page_friends = new mainwindow;
    //    mainwindow * page_groups = new mainwindow;
    //    mainwindow * page_research = new mainwindow;

    //页面添加到切换区




    //    qDebug() << "1页面索引: " <<ui->stack->addWidget(page_message->show_message());
    //    qDebug() << "2页面索引: " <<ui->stack->addWidget(page_friends->show_friends());
    //    qDebug() << "3页面索引: " <<ui->stack->addWidget(page_groups->show_groups());
    //    qDebug() << "4页面索引: " <<ui->stack->addWidget(page_research->show_result());



    qDebug() << "页面索引总数: " << ui->stack->count();
    //绑定页面和按键
    connect(ui->abutton,&QPushButton::clicked,this,&firstwindow::switchPage);
    connect(ui->bbutton,&QPushButton::clicked,this,&firstwindow::switchPage);
    connect(ui->cbutton,&QPushButton::clicked,this,&firstwindow::switchPage);
    connect(ui->dbutton,&QPushButton::clicked,this,&firstwindow::switchPage);


    //自定数据库
    //QStringList word_list;
    // word_list<<"Java"<<"C++"<<"C#"<<"PHP"<<"Perl"<<"Python"<<"Delphi"<<"Ruby";
    //模糊匹配（
    //QCompleter *NewFind = new QCompleter(word_list);
    //ui->comboBox->setCompleter(NewFind);

    Clock = new QTimer;
    connect(Clock,&QTimer::timeout,this,&firstwindow::up_date);
    Clock->start(2000);
}

firstwindow::~firstwindow()
{
    delete ui;
}

void firstwindow::show_friends()
{

    if(page_friends != nullptr){
        delete page_friends;
    }
    page_friends = new QWidget();

    QWidget *scrollareacontent;//滚动框的内容页面
    QScrollArea *scrollarea;//滚动框的区域
    QWidget* page = new QWidget(page_friends);//滚动框的总页面


    //page在page_friends平铺
    QVBoxLayout *m_layout = new QVBoxLayout(page_friends);
    m_layout->setContentsMargins(0, 0, 0, 0);
    m_layout->setSpacing(0);
    m_layout->addWidget(page);
    page_friends->setLayout(m_layout);

    //设置带滚动区域和滚动内容界面
    scrollarea = new QScrollArea(page);
    scrollarea->setWidgetResizable(true);
    scrollarea->setGeometry(0,0,page->width(),page->height());
    scrollareacontent = new QWidget();
    scrollarea->setWidget(scrollareacontent);

    // 将 QScrollArea 放置在一个布局中，以便自动随窗口大小变化
    QVBoxLayout* scrollLayout = new QVBoxLayout();
    scrollLayout->addWidget(scrollarea);
    page->setLayout(scrollLayout);

    QVBoxLayout* playout = new QVBoxLayout(page);
    playout->setAlignment(Qt::AlignTop );//垂直靠上
    scrollareacontent->setLayout(playout);
    scrollareacontent->setStyleSheet("background-color: transparent;");

    //根据组数遍历组，同时查找组的成员构成列表（测试直接新建）
    QMap<QString,QVBoxLayout*> jobList;
    for(auto f :userMap){
        jobList.insert(f->job,nullptr);
    }
    //int Num_lists = jobList.size();
    foreach(const QString &key, jobList.keys()){
        list_button* Button = new list_button(scrollareacontent);
        Button->SetImageLabel(QPixmap(":/new/prefix1/icon/005.png"));
        Button->setFixedHeight(50);
        Button->SetTextLabel(key);
        //查找组的成员形成一个界面
        Button->sizeWidget = new QWidget(scrollareacontent);
        Button->sizeWidget->setVisible(false);

        //好友列表垂直布局
        QVBoxLayout* sizeLayout = new QVBoxLayout;
        jobList[key] = sizeLayout;
        //int Max_num = 3;
        Button->sizeWidget->setLayout(sizeLayout);
        playout->addWidget(Button);
        playout->addWidget(Button->sizeWidget);

        connect(Button, &list_button::clicked, [Button]() {
            if (Button->clicks % 2 == 0)
            {
                Button->SetImageLabel(QPixmap(":/new/prefix1/icon/005.png"));
                //m_sizeList偶数屏蔽Size列表界面，奇数显示Size列表界面
                Button->sizeWidget->setVisible(false);
            }
            else
            {
                Button->SetImageLabel(QPixmap(":/new/prefix1/icon/006.png"));
                Button->sizeWidget->setVisible(true);
            }
            Button->clicks++; });
    }
    for(auto f :userMap){
        small_message* smg = new small_message(f);
        smg->setMaximumSize(smg->size());
        smg->setMinimumSize(smg->size());
        jobList[f->job]->addWidget(smg);
    }
    playout->addStretch();
    playout->setSpacing(0);
    ui->stack->addWidget(page_friends);
}

void firstwindow::show_message()
{

    if(page_message != nullptr){
        delete page_message;
    }
    page_message = new QWidget();
    QWidget *scrollareacontent;//滚动框的内容页面
    QScrollArea *scrollarea;//滚动框的区域
    QWidget* page = new QWidget(page_message);//滚动框的总页面


    //page在page_friends平铺
    QVBoxLayout *m_layout = new QVBoxLayout(page_message);
    m_layout->setContentsMargins(0, 0, 0, 0);
    m_layout->setSpacing(0);
    m_layout->addWidget(page);
    page_message->setLayout(m_layout);

    //设置带滚动区域和滚动内容界面
    scrollarea = new QScrollArea(page);
    scrollarea->setWidgetResizable(true);
    scrollarea->setGeometry(0,0,page->width(),page->height());
    scrollareacontent = new QWidget();
    scrollarea->setWidget(scrollareacontent);

    // 将 QScrollArea 放置在一个布局中，以便自动随窗口大小变化
    QVBoxLayout* scrollLayout = new QVBoxLayout();
    scrollLayout->addWidget(scrollarea);
    page->setLayout(scrollLayout);

    // message的垂直布局
    message_playout->setAlignment(Qt::AlignTop );//垂直靠上
    scrollareacontent->setLayout(message_playout);
    scrollareacontent->setStyleSheet("background-color: transparent;");


    message_playout->addStretch();
    message_playout->setSpacing(0);


    ui->stack->addWidget(page_message);

    //测试
    //    user* user1 = new user("001");
    //    user* user2 = new user("002");
    //    add_message(user1,"sdaf","456:456");
    //    add_message(user2,"adfasdfads","19:15");
    //    add_message(user1,"guikgjknk","3:49");
}

void firstwindow::add_message(user* send_user,QString latest_message, QString latest_time){
    qDebug()<<"add_message";
    qDebug()<<"加之前"<<message_playout->count();
    //寻找目标
    message* new_message = NULL;
    //     遍历布局中的 widget
    for (int i = 0; i < message_playout->count(); ++i) {
        QLayoutItem* layoutItem = message_playout->itemAt(i);
        if (layoutItem) {
            QWidget* widget = layoutItem->widget();
            if (widget) {
                // 检查 widget 是否是 Message 类型
                message* messageWidget = qobject_cast<message*>(widget);
                if (messageWidget) {
                    // 在此处检查满足条件 A 的条件
                    if (messageWidget->user_id == send_user->id) {
                        message_playout->removeWidget(widget);
                        new_message = messageWidget;
                        //                        delete widget;
                    }
                }
            }
        }
    }
    if(new_message!=NULL){
        new_message->set_history(latest_message);
        new_message->set_time(latest_time);
        new_message->set_readnum(true);
    }else{
        new_message = new message(send_user,latest_message,latest_time);
        new_message->set_readnum(true);
    }

    message_playout->insertWidget(0, new_message);
    qDebug()<<"加了以后"<<message_playout->count();
}

void firstwindow::show_groups()
{

    if(page_groups != nullptr){
        delete page_groups;
    }
    page_groups = new QWidget();

    QWidget *scrollareacontent;//滚动框的内容页面
    QScrollArea *scrollarea;//滚动框的区域
    QWidget* page = new QWidget(page_groups);//滚动框的总页面


    //page在page_friends平铺
    QVBoxLayout *m_layout = new QVBoxLayout(page_groups);
    m_layout->setContentsMargins(0, 0, 0, 0);
    m_layout->setSpacing(0);
    m_layout->addWidget(page);
    page_groups->setLayout(m_layout);

    //设置带滚动区域和滚动内容界面
    scrollarea = new QScrollArea(page);
    scrollarea->setWidgetResizable(true);
    scrollarea->setGeometry(0,0,page->width(),page->height());
    scrollareacontent = new QWidget();
    scrollarea->setWidget(scrollareacontent);

    // 将 QScrollArea 放置在一个布局中，以便自动随窗口大小变化
    QVBoxLayout* scrollLayout = new QVBoxLayout();
    scrollLayout->addWidget(scrollarea);
    page->setLayout(scrollLayout);

    QVBoxLayout* playout = new QVBoxLayout(page);
    playout->setAlignment(Qt::AlignTop );//垂直靠上
    scrollareacontent->setLayout(playout);
    scrollareacontent->setStyleSheet("background-color: transparent;");


    /*这段注释掉的是获取好友分组和好友列表
    这里需要同理获得群组的分组和列表（small_message应该传入的是group中的id而不是user_id）*/


    //    根据组数遍历组，同时查找组的成员构成列表（测试直接新建）
    QMap<QString,QVBoxLayout*> group_cat_List;
    for(auto f :groupMap){
        group_cat_List.insert(f->job,nullptr);
    }
    //int Num_lists = jobList.size();
    foreach(const QString &key, group_cat_List.keys()){
        list_button* Button = new list_button(scrollareacontent);
        Button->SetImageLabel(QPixmap(":/new/prefix1/icon/005.png"));
        Button->setFixedHeight(50);
        Button->SetTextLabel(key);
        //查找组的成员形成一个界面
        Button->sizeWidget = new QWidget(scrollareacontent);
        Button->sizeWidget->setVisible(false);

        //好友列表垂直布局
        QVBoxLayout* sizeLayout = new QVBoxLayout;
        group_cat_List[key] = sizeLayout;
        //int Max_num = 3;
        Button->sizeWidget->setLayout(sizeLayout);
        playout->addWidget(Button);
        playout->addWidget(Button->sizeWidget);

        connect(Button, &list_button::clicked, [Button]() {
            if (Button->clicks % 2)
            {
                Button->SetImageLabel(QPixmap(":/new/prefix1/icon/005.png"));
                //m_sizeList偶数屏蔽Size列表界面，奇数显示Size列表界面
                Button->sizeWidget->setVisible(false);
            }
            else
            {
                Button->SetImageLabel(QPixmap(":/new/prefix1/icon/006.png"));
                Button->sizeWidget->setVisible(true);
            }
            Button->clicks++; });
    }
    for(auto g :groupMap){
        small_message* smg = new small_message(g);
        smg->setMaximumSize(smg->size());
        smg->setMinimumSize(smg->size());
        group_cat_List[g->job]->addWidget(smg);
    }

    playout->addStretch();
    playout->setSpacing(0);

    ui->stack->addWidget(page_groups);



}


//展示展示
void firstwindow::show_me(){
    QPixmap picture = me->picture.scaled(ui->image->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    int width = ui->image->size().width();
    int height = ui->image->size().height();
    //面向结果设置图片大小xs
    if(width>height) height = width;
    else width = height;
    QPixmap image(width,height);
    image.fill(Qt::transparent);

    QPainterPath painterPath;
    painterPath.addEllipse(0, 0, width, height);

    QPainter painter(&image);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
    painter.setClipPath(painterPath);
    painter.drawPixmap(0, 0, width, height, picture);
    ui->image->setPixmap(image);
    QFont font;
    font.setPointSize(18);
    ui->name->setFont(font);
    ui->name->setText(me->name);

    ui->head->installEventFilter(this);    // 安装事件过滤器


}

void firstwindow::on_abutton_clicked()
{
    qDebug() << "按钮1信号绑定成功";
}

void firstwindow::on_bbutton_clicked()
{
    qDebug() << "按钮2信号绑定成功";
}

void firstwindow::on_cbutton_clicked()
{
    qDebug() << "按钮3信号绑定成功";
}

void firstwindow::on_dbutton_clicked()
{
    qDebug() << "按钮搜索信号绑定成功";
    show_search();
}

void firstwindow::switchPage(){

    QPushButton *button = qobject_cast<QPushButton*>(sender());
    if(button==ui->abutton)
        ui->stack->setCurrentIndex(0);
    else if(button==ui->bbutton)
        ui->stack->setCurrentIndex(1);
    else if(button==ui->cbutton)
        ui->stack->setCurrentIndex(2);
    else if(button==ui->dbutton){
        ui->stack->setCurrentIndex(3);
        //show_search();
    }
}
void firstwindow::up_date()
{
    QJsonObject uid_bag;
    uid_bag.insert("UID",use_uid);
    uid_bag.insert("last_message_id",QString::number(db.GetMaxMessageId()));
    uid_bag.insert("last_user_id",user_list_edition);
    uid_bag.insert("last_group_id","1");
    QJsonDocument jsonDocument;
    jsonDocument.setObject(uid_bag);
    emit heart_jump(jsonDocument.toJson());

}

void firstwindow::getUpdateMessage(const QJsonArray &msg_list)
{
    int num = msg_list.size();
    for (int i =0; i < num; i++)
    {
        QJsonObject MessagePack = msg_list.at(i).toObject();
        Message Msg;
        Msg.tid = MessagePack.value("TID").toString().toInt();
        Msg.rid = MessagePack.value("RID").toString().toInt();
        Msg.msg = MessagePack.value("content").toString();
        Msg.id = MessagePack.value("MID").toString().toInt();
        Msg.time = QDateTime::fromString(MessagePack.value("time").toString(), "yyyy-MM-dd hh:mm:ss");
        db.AddMessage(Msg);

        if(Msg.rid >= 800000){
            group* g = groupMap.value(MessagePack.value("RID").toString());
            ChatWidget* cw = g->chat;
            if(cw && cw->isVisible()){
                cw->receiveMessage(Msg);
                g->show_chat();
            }
            else{
                Msg.msg= userMap[MessagePack.value("TID").toString()]->name+" : "+Msg.msg;
                add_message(g,Msg.msg,Msg.time.toString());
            }
        }
        else{
            user* u= userMap.value(MessagePack.value("TID").toString());
            ChatWidget* cw  =u->chat;
            if(cw && cw->isVisible()){
                cw->receiveMessage(Msg.msg);
                u->show_chat();
            }
            else{
                add_message(u,Msg.msg,Msg.time.toString());
            }
        }

    }
}
void firstwindow::getUpdateUserlist(const QJsonArray &user_list)
{
    for(int i=0;i<user_list.size();i++){
        QJsonObject change_pack = user_list.at(i).toObject();
        if(change_pack.value("operator").toString()=="offline"){
//            userMap[change_pack.value("UID").toString()]->set_ip("-1");
//            userMap[change_pack.value("UID").toString()]->chat->updateIP("-1");
            user* u =  userMap[change_pack.value("UID").toString()];
            u->set_ip("-1");
            if(u->chat)
            {
                u->chat->updateIP("-1");
            }
        }
        else if(change_pack.value("operator").toString()=="online"){
            user* u =  userMap[change_pack.value("UID").toString()];
            u->set_ip(change_pack.value("ip").toString());
            if(u->chat)
            {
                u->chat->updateIP(change_pack.value("ip").toString());
            }
        }
        else if(change_pack.value("operator").toString()=="alter"){
            userMap[change_pack.value("UID").toString()]->set_ip(change_pack.value("ip").toString());
            userMap[change_pack.value("UID").toString()]->set_name(change_pack.value("name").toString());
            ui->stack->removeWidget(page_search);
            ui->stack->removeWidget(page_groups);
            ui->stack->removeWidget(page_friends);

            show_friends();
            show_groups();
            show_search();
        }
        else if(change_pack.value("operator").toString()=="delete"){
            userMap.remove(change_pack.value("UID").toString());
        }
        else if(change_pack.value("operator").toString()=="add"){
            user* newUser = new user(change_pack.value("UID").toString(),
                                     change_pack.value("name").toString(),
                                     change_pack.value("ip").toString(),
                                     change_pack.value("job").toString());
            userMap.insert(change_pack.value("UID").toString(), newUser);

            ui->stack->removeWidget(page_search);
            ui->stack->removeWidget(page_groups);
            ui->stack->removeWidget(page_friends);

            show_friends();
            show_groups();
            show_search();
        }
        if(user_list_edition<change_pack.value("list_no").toInt())
            user_list_edition = change_pack.value("list_no").toInt();
    }
}
void firstwindow::getUpdateFileLists(const QJsonArray &fmsg_list)
{
    int num = fmsg_list.size();
    for (int i =0; i < num; i++)
    {
        QJsonObject Friend = fmsg_list.at(i).toObject();
        Message Msg;
        Msg.tid = Friend.value("TID").toString().toInt();
        Msg.rid = Friend.value("RID").toString().toInt();
        Msg.msg = Friend.value("content").toString();
        QString rfileName = Msg.msg.section("##",0,0);
        int rfileSize = Msg.msg.section("##",1,1).toInt();
        QString type = Msg.msg.section("##",2,2);
        Msg.id = Friend.value("MID").toString().toInt();
        Msg.time = QDateTime::fromString(Friend.value("time").toString(), "yyyy-MM-dd hh:mm:ss");
        db.AddMessage(Msg);

        QJsonObject rf_bag;
        rf_bag.insert("MID",QString::number(Msg.id));
        rf_bag.insert("UID",QString::number(Msg.rid));
        QJsonDocument doc;
        doc.setObject(rf_bag);

        user* u= userMap.value(Friend.value("TID").toString());
        ChatWidget* cw  =u->chat;
        if(cw && cw->isVisible()){
            //cw->receiveMessage(Msg.msg);
            if(type == "1")
                cw->beforeReceivePicture(rfileName,doc.toJson(),rfileSize);
            else
                cw->beforeReceiveFile(rfileName,doc.toJson(),rfileSize);
            cw->beforeReceiveFile(rfileName,doc.toJson(),rfileSize);
            u->show_chat();
        }
        else{
            add_message(u,Msg.msg.section("##",0,0),Msg.time.toString());
        }

        //        ui->filelist->addItem(tr("%1##%2").arg(rfileName).arg(QString::number(Msg.id)));
        //        ui->history->appendPlainText(id_list->value(QString::number(Msg.tid)).toString()+"[in]"+rfileName+" "+QString::number(rfileSize));}
    }
}

bool firstwindow::eventFilter(QObject* obj, QEvent* event)
{
    if (obj == ui->head) {
        //单击
        if (event->type() == QEvent::MouseButtonPress) {
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            // 在左键点击时，打开聊天框
            qDebug() << "2dudu";
            if (mouseEvent->button() == Qt::LeftButton) {
                //打开自己的信息界面
                me->show_info();
            }
            // 在右键点击时弹出选择窗口
            else if (mouseEvent->button() == Qt::RightButton) {

                QPoint pos = mapToGlobal(mouseEvent->pos());
                QMenu contextMenu;
                QAction action_one("修改昵称", this);
                qDebug()<<"新界面";
                connect(&action_one, &QAction::triggered, [this]() {
                    // 处理选择窗口的操作
                    change_namewindow = new QWidget();
                    change_namewindow->setWindowTitle("修改昵称");
                    change_namewindow->setWindowIcon(QIcon(":/new/prefix1/images/icons_head.png"));

                    QVBoxLayout *layout = new QVBoxLayout;

                    nicknameLineEdit = new QLineEdit;
                    layout->addWidget(nicknameLineEdit);
                    QPushButton *okButton = new QPushButton("OK");

                    connect(okButton, &QPushButton::clicked,this,&firstwindow::changeName);
                    connect(this, &firstwindow::ser_changerName,m_socket,&SerSocket::ClientSendingText);
                    layout->addWidget(okButton);

                    change_namewindow->setLayout(layout);
                    change_namewindow->show();


                    connect(okButton, &QPushButton::clicked, this, &firstwindow::on_namebutton_clicked);


                    // QMessageBox::information(this, "窗口", "您选择了详细信息");
                });
                contextMenu.addAction(&action_one);

                QAction action_two("注销账户", this);

                connect(&action_two, &QAction::triggered, [this]() {
                    // 处理选择窗口的操作
                    QWidget* delete_window = new QWidget();
                    delete_window->setWindowTitle("账户注销");
                    delete_window->setWindowIcon(QIcon(":/new/prefix1/images/icons_head.png"));

                    QVBoxLayout *layout = new QVBoxLayout;

                    QLabel* text = new QLabel;
                    text->setText("是否确定注销？注销后无法 恢复");
                    layout->addWidget(text);
                    QPushButton *okButton = new QPushButton("是");
                    layout->addWidget(okButton);
                    QPushButton *noButton = new QPushButton("否");
                    layout->addWidget(noButton);

                    delete_window->setLayout(layout);
                    delete_window->show();

                    //后端删除接口use_id

                    connect(okButton, &QPushButton::clicked, this, &firstwindow::deleteitself);
                    connect(this,&firstwindow::deleteItself,m_socket,&SerSocket::ClientSendingText);

                    connect(okButton, &QPushButton::clicked, this, &QWidget::close);
                    connect(okButton, &QPushButton::clicked, delete_window, &QWidget::close);
                    connect(noButton, &QPushButton::clicked, delete_window, &QWidget::close);

                    // QMessageBox::information(this, "窗口", "您选择了详细信息");
                });
                contextMenu.addAction(&action_two);
                contextMenu.exec(pos);
                return true;
            }
        }
        else {
            return false;
        }
    }
    return QWidget::eventFilter(obj, event);
}

void firstwindow::on_namebutton_clicked()
{
    QString new_name = nicknameLineEdit->text();

    if (!new_name.isEmpty())
    {
        // 在这里处理新昵称
        me->set_name(new_name);
        show_me();
        // 传到线上去
        use_name = new_name;
        QMessageBox::information(this,"修改认证","修改成功");
    }
    else{
        QMessageBox::information(this,"修改认证","修改失败，名字不能为空");
    }
    change_namewindow->close();
}

void firstwindow::show_search()
{

    if(page_search!=nullptr){
        delete  page_search;
    }
    page_search = new QWidget();


    QWidget *scrollareacontent;//滚动框的内容页面
    QScrollArea *scrollarea;//滚动框的区域
    QWidget* page = new QWidget(page_search);//滚动框的总页面

//    qDebug()<<"qian"<<page_search->layout();
//    if(page_search->layout()){
//        delete page_search->layout();
//        qDebug()<<"hou"<<page_search->layout();
//    }

    QVBoxLayout *m_layout = new QVBoxLayout(page_search);
    m_layout->setContentsMargins(0, 0, 0, 0);
    m_layout->setSpacing(0);
    m_layout->addWidget(page);
    page_search->setLayout(m_layout);

    //设置带滚动区域和滚动内容界面
    scrollarea = new QScrollArea(page);
    scrollarea->setWidgetResizable(true);
    scrollarea->setGeometry(0,0,page->width(),page->height());
    scrollareacontent = new QWidget();
    scrollarea->setWidget(scrollareacontent);

    // 将 QScrollArea 放置在一个布局中，以便自动随窗口大小变化
    QVBoxLayout* scrollLayout = new QVBoxLayout();
    scrollLayout->addWidget(scrollarea);
    page->setLayout(scrollLayout);

    QVBoxLayout* playout = new QVBoxLayout(page);
    playout->setAlignment(Qt::AlignTop );//垂直靠上
    scrollareacontent->setLayout(playout);
    scrollareacontent->setStyleSheet("background-color: transparent;");

    //找到对应用户产生small_meseage加入playout中
    QString search_name = ui->search_box->text();
    qDebug() << search_name << "searchname";
//    QString search_name = "i";

    QVector<int> ids = db.GetIdsByName(search_name);
    if(ids.size()){
        //找到了
        for(auto id:ids){

            small_message* search_ans2 = new small_message(userMap[QString::number(id)]);
            search_ans2->setMaximumSize(search_ans2->size());
            search_ans2->setMinimumSize(search_ans2->size());
            playout->addWidget(search_ans2);

        }
    }
    else{
        //没找到
        QLabel* end = new QLabel;
        end->setText("——没有找到匹配的对象——");
        playout->addWidget(end);
    }

    playout->addStretch();
    playout->setSpacing(0);

    ui->stack->addWidget(page_search);
}
void firstwindow::changeName(){
   //todo
    QJsonObject nm_bag;
    nm_bag.insert("UID",use_uid);
    nm_bag.insert("uName",nicknameLineEdit->text());
    QJsonDocument doc;
    doc.setObject(nm_bag);
    emit ser_changerName(doc.toJson(),0x0C);
}
void firstwindow::deleteitself()
{
    QJsonObject it_bag;
    it_bag.insert("UID",use_uid);
    QJsonDocument doc;
    doc.setObject(it_bag);
    emit deleteItself(doc.toJson(),0x0E);
}
